package com.seata.dubbo.provider.dubbo;


import com.seata.dubbo.api.OrderApi;
import com.seata.dubbo.db.entity.Order;
import com.seata.dubbo.db.service.IAccountService;
import com.seata.dubbo.db.service.IOrderService;
import com.seata.dubbo.db.service.IStorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;

/**
 *
 */
@DubboService
public class OrderApiImpl implements OrderApi {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderApiImpl.class);

    @Value("${server.port}")
    private Integer port;

    @Autowired
    IOrderService orderService;


    @Autowired
    IAccountService accountService;


    @Autowired
    IStorageService storageService;

    @Override
    public String demo() {
        return "port= " + port;
    }

    @Override
    public String create(Order order) {
        LOGGER.info("------->交易开始");

        orderService.createOrder(order);

        LOGGER.info("------->交易结束");

        return "";
    }

    @Override
    @GlobalTransactional(name = "fsp_create_order", timeoutMills = 60000)
    public String createOrder(Order order) {
        LOGGER.info("------->交易开始");

        //
        orderService.createOrder(order);

        //

        //远程方法 扣减库存
        storageService.decrease(order.getProductId(), order.getCount());

        //远程方法 扣减账户余额
        accountService.decrease(order.getUserId(), order.getMoney());

        LOGGER.info("------->交易结束");

        return null;
    }


    @Override
    public String updateOrder(Long userId, BigDecimal money, Integer status) {
        orderService.updateOrder(userId, money, status);
        return "订单状态修改成功";
    }

    @Override
    public String changeCount(Integer count) {
        orderService.changeCount(count);
        return "更新成功";
    }
}
